//
//  DispatchQueue+ALExtension.swift
//  ALCore
//
//  Created by IdeaBank on 2023/12/18.
//

import Foundation

public extension DispatchQueue {

    /// 判断当前队列是否为主队列
    static var isMainQueue: Bool {
        enum Static {
            static var key: DispatchSpecificKey<Void> = {
                let key = DispatchSpecificKey<Void>()
                DispatchQueue.main.setSpecific(key: key, value: ())
                return key
            }()
        }
        return DispatchQueue.getSpecific(key: Static.key) != nil
    }

    /// 判断当前队列是否为指定队列
    static func isCurrent(_ queue: DispatchQueue) -> Bool {
        let key = DispatchSpecificKey<Void>()

        queue.setSpecific(key: key, value: ())
        defer { queue.setSpecific(key: key, value: nil) }

        return DispatchQueue.getSpecific(key: key) != nil
    }

    /// 延迟指定时间后执行闭包任务
    static func asyncAfter(delay seconds: Double, execute work: @escaping () -> Void) {
        DispatchQueue.main.asyncAfter(deadline: .now() + seconds, execute: work)
    }

    /// 在主线程中执行闭包任务
    static func runInMainThread(_ work: @escaping () -> Void) {
        if Thread.isMainThread {
            work()
        } else {
            DispatchQueue.main.sync(execute: work)
        }
    }
}

//MARK: - 基础功能
extension ALPrefixWrapper where Base: DispatchQueue {

    /// 异步延迟执行事件 & 可回到主线程执行另外事件 延迟默认 0s
    /// - Parameters:
    ///   - delay: 延迟时间
    ///   - subBlock: 子线程事件
    ///   - mainBlock: 主线程事件
    public static func async(
        _ delay: TimeInterval = 0,
        subBlock: @escaping () -> Void,
        mainBlock: (() -> Void)?
    ) {
        let item = DispatchWorkItem(block: subBlock)
        DispatchQueue.global().asyncAfter(
            deadline: .now() + delay,
            execute: subBlock
        )
        if let main = mainBlock {
            item.notify(queue: DispatchQueue.main, execute: main)
        }
    }
}
